package com.ctrip.study.crawler.priceImage;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

public class CharacterProcess {
	private static Map<BufferedImage, String> characterMap = new HashMap<BufferedImage, String>();
	private static final int[] DEC_TAB = { -1, -1, -1, -1, -1, -1, -1, -1, -1,
			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
			-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
			14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
			-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
			42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1,
			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			-1, -1, -1, -1, -1, -1, -1, };
	static {
		loadTrainedChar();
	}

	private static void loadTrainedChar() {
		characterMap
				.put(base64ToBufferedImage("iVBORw0KGgoAAAANSUhEUgAAABEAAAAlCAYAAACkhgJBAAAAS0lEQVR42mP4TwXAMGrIqCGjhowaMmrIqCFD2pB/3VlwTJEh/9MYKDeEYpeAwcn9lBvyb/VMCg25cREcJiDXkB8m25aD8WiKpRwAAOSAueAS48+oAAAAAElFTkSuQmCC"),
						",");
		characterMap
				.put(base64ToBufferedImage("iVBORw0KGgoAAAANSUhEUgAAABEAAAAlCAYAAACkhgJBAAAAM0lEQVR42mP4TwXAMGrIqCGjhowaMmrIqCFD2pB/3VlwTJEh/9MYKDeEYpeMRvGoITgAAIHVwMw3SVZNAAAAAElFTkSuQmCC"),
						".");
		characterMap
				.put(base64ToBufferedImage("iVBORw0KGgoAAAANSUhEUgAAABEAAAAlCAYAAACkhgJBAAAA3UlEQVR42mP4TwXAMGrIkDLk65f//w5s+f9vbuv/f91ZCAzk/794AiyP35AbF8Ea/qcx4MRgeaA67IZ8eIdhALJLMAwCqscw5N/qmaiKTu5HOB1EA/nIhv3bthzNEFA4QBWA6VfPsYfg0weoFqEYAgowLDZgA8guhoUN2BCwRjQJnAAkj2YhxBBQ9MEMweUVGADJwwwB6YMbghweRAB09aOG0NQQqkQxNRIbNgmcXkG2EJRdSM6AQHEUddBcTn5RAFKPUSghZXOyCyXqFI9EFNQgccIF9WgNOGoIdgAAfkP/l2+IlDMAAAAASUVORK5CYII="),
						"0");
		characterMap
				.put(base64ToBufferedImage("iVBORw0KGgoAAAANSUhEUgAAABEAAAAlCAYAAACkhgJBAAAAcElEQVR42mP4TwXAMGrIkDbk6YP//7qzwJhsQ/7Nbf3/P42BfENgBpBnyK9fKAaQbsi9mxANSAaQZMi/1TNRNV08ATeQeENgGkCGfXiHKka0IaBwuHHxP1aDKYriUUNGDRk1ZGANobigHq0BRw0BAgDzNWh2gvRC6QAAAABJRU5ErkJggg=="),
						"1");
		characterMap
				.put(base64ToBufferedImage("iVBORw0KGgoAAAANSUhEUgAAABEAAAAlCAYAAACkhgJBAAAA3ElEQVR42mP4TwXAMGrIkDLk6YP//1bP/P+vOwsVA8X+37hI2BCwwjQGvBisBpch2AyAuQJDfG4rFkNAzkRWtG35//8f3iFUAdlgMWTDLp5ANQTFFUiS6ADZIGTXQAxBCkC84OsXuPeQ1ZIcxYPEEKQI+HdgC3mGgAMT5gpg+JBsCEoUo8UgA6kGgNmkZkBCBhA0hBgD8BpCrAHYDXn1HB4LhLIBdkNABiAnpns3SSyU0A0A8kku2VASEgkGIAwB+RtLYUQIoxYFyAFJJMY0hEib8bpktAYcNYQAAAD2ayGix9pZ6wAAAABJRU5ErkJggg=="),
						"2");
		characterMap
				.put(base64ToBufferedImage("iVBORw0KGgoAAAANSUhEUgAAABEAAAAlCAYAAACkhgJBAAABC0lEQVR42u2Vrw7CQAzG97QI3gPFEyDQCCzBggQ5NwzBEBIEQYC9cl+zHe3tFnrLDMma1Gx3v339u4IGsGKE/BXk/SK3XZGbT7WvF0RVaYAcd3yBJkWnu+WM6H7rgHhA64JQEj+HYg1BCOIgwlFfw4VIJZ+REH6QeNmy60WrURAfZ5AtZKasUdOCmO18+ipBtbIgPj9uv9Eqng8bJFkZlBi5MXUsqtPVJwjLCuGENx4r8uH1SqxsBfY6rOwBVD1VVyh/ilGVqOF6rYK44YaDqGn90fZqflDuAEGCLANYz1moTnkQ4Qh6AIm2bs5IQHIAuXlylpLYNwOvR7moMbFix7DjsmlRj3/AEZK2D2FGFRSJghUXAAAAAElFTkSuQmCC"),
						"3");
		characterMap
				.put(base64ToBufferedImage("iVBORw0KGgoAAAANSUhEUgAAABEAAAAlCAYAAACkhgJBAAAAwklEQVR42mP4TwXAMGrIsDHkxsX//7qzwJg8Q149h2hOYyDfkH9zW8EGkG3Iv9Uz4QaQZci/A1tQDCDdkHs3ERqBriE9TD68Q2gChcevX6QbAgtIsAaggWAxUgz5t205IgyAaQMuTrQhF08gwgEUqMiGE2XI0wcoAYnhQoKGfP2CqggYkCQbghKQwCSONazwGYISkKAwwRVjeA2BSsIU4MLoqRZmGIYhpGAMQ4jBeF1CdHFAaXkyTA2hrKAerQFHsiEAZOEgBOBtaswAAAAASUVORK5CYII="),
						"4");
		characterMap
				.put(base64ToBufferedImage("iVBORw0KGgoAAAANSUhEUgAAABEAAAAlCAYAAACkhgJBAAAA+ElEQVR42u2VvwrCMBDG87QOvoeTT+Dg7OAqrro6ujm6iOAgDrrmzFfa9HKXYHs4KCQQCm345bvv/tTRF5arkH+B+Pl01NaQ25Vo4gbvPOSwSw6YlPjtqr/pdLR54pezHvK4GyGQJ2IdB8HNnR9QZILAgw6y3xC9ns0zMRJwmF+E8MysFzG0YmqF8U6ZWkizAjKQU5UalNDlrDWHd803riiEbeqdBAT/TA0IlSKTpi6WNfVjkCSVrePFxQsTJkdIxvGiCl5Tba046XgEyU5GnTAA77H8PMlUrSp9FnY6Y6Hg01iEAqFSZyccgCocVu1QmHj1D1ghQ9YbmYgFZj0m9H8AAAAASUVORK5CYII="),
						"5");
		characterMap
				.put(base64ToBufferedImage("iVBORw0KGgoAAAANSUhEUgAAABEAAAAlCAYAAACkhgJBAAABH0lEQVR42u2Vrw7CQAzG72kRvAeKJ0CgEViCRmLnkDOEBEEQYCZWrt0d6/V6fwgYkjVZSC67X7+234qBH4SZIH8HeT6gP+ygXy+gX87HZ7sCODUVkOZIF2Bmkg/BUhDMHl1wKqLz/UaBnNv4petlzHC/DWcchnc4hCQqWWRwkC/L+CxcPjY2Gdh01uwRYptZoyI7Yl6Kr/NziPXDG4KlYVg/IDzyiZJkgLgR0m/Xhco0n4iSI0gwJd7Akk/kS1SetLf1TNYnHEKATCR9EigpTUd6Sk7HH5YiGIT0yVcQaqIvR9kXyXJc/4xKt15JquAWwNURQNguqRkx/1DDpcTtXzAbT2JyclXLI1Co1Be19Ur08eHSxpKVXTP9A06QmngBMeDtvLifpJgAAAAASUVORK5CYII="),
						"6");
		characterMap
				.put(base64ToBufferedImage("iVBORw0KGgoAAAANSUhEUgAAABEAAAAlCAYAAACkhgJBAAAAxElEQVR42mP4TwXAMGrIUDDkX3cWWRjDkP9pDCRhrIYQbTvMkLmtZIbJxRMIV3x4R4YhTx8gvAMyjOTY+fUL7pV/q2eSF8X/ti1HeOPrFzIMuXcT4Y2T+8lLbOBYQIpS0g0B2YzHFUQZAg9MHK4gbMiNi4iEdWALeYaghAVajBBnCCg1oiVvkg0BOx9L6iTNEOQAxeMV3IYANRETK/gNQY4VUHInxxBSwgO3IdCoBeNXz8k0hIRAxWsIckE8WgOOGkINQwAS/U+9JC/PAgAAAABJRU5ErkJggg=="),
						"7");
		characterMap
				.put(base64ToBufferedImage("iVBORw0KGgoAAAANSUhEUgAAABEAAAAlCAYAAACkhgJBAAABGElEQVR42u1VMQ7CMAzMaxn4BxMvYGBmYEWsMMLYDRbEgpAYEAOsDbbbkkvipK3UBamRIjXJ9eL6zq6xAwwzkvwdyXFny+XMlvOpm7S2xaEDyeMuL9iJSU45J5xO8npGBBhJRPR5xyTleuFAHPrt6sdMa9lvMNuVQoK3hQRA5EWTIsFDbWg4RwKhdoqE8VFiL+deORG8KvGp8HKjqSPPhMubjW7wbgylhQhUEpQ56xOQN5lYAQWulJyEXvJIqFZ+hwzMSYzR1rkxkbxk/+xQZDZ9jJYy3PAknT6Hz4P6qUhYjYR8ucQ22Eod6g2eKxkY2p4bFl4GPcWg5TWHamZDeVtrJ2n91trhT9tv1EbN+9gWxz/gSNJnfAFG8u2nwf5zbgAAAABJRU5ErkJggg=="),
						"8");
		characterMap
				.put(base64ToBufferedImage("iVBORw0KGgoAAAANSUhEUgAAABEAAAAlCAYAAACkhgJBAAABIklEQVR42u2VoQ4CMQyG97QI3gPFEyDQCCzBggR5DokhJAiCAHPiyrq7bW3XDY6cIbkmFwJ03/52/3oGBggzQv4K8npCs99As5xBM5/GZ7sCuJy/gJwqtwAmJvs4WBZSHdIFRAn73apMIVgCSXRJUvrt2qrwObZkBmF/il1k+Fy3qd08QqjcTPNCPO4xF1sgIe7ziwj568UAkK70tByUWwosl5ye3ljFB0wF7q5BKD2AZIPtdwpIIUJNyWzYTNlDo3kga3k8jbouQ4Lsbrfw4GJ7r6S72en0Cno6v0JYyccd90loYHcfPhmNeqqFYM3K7UyCjAtv+bxPEEQViTEgL2r0CVFTGki0F+p4lCDNfP76lwc1zlnpExzassTxDThCesYbuhzvoabJK4kAAAAASUVORK5CYII="),
						"9");
	}

	private static BufferedImage base64ToBufferedImage(String base64Code) {
		try {
			return ImageIO.read(new ByteArrayInputStream(decode(base64Code)));
		} catch (IOException e) {
			return null;
		}
	}

	private static byte[] decode(String str) {
		char[] buffer = str.toCharArray();
		int length = 0;
		for (int i = 0; i < buffer.length; i++) {
			int dec = DEC_TAB[buffer[i] & 0xFF];
			if (dec != -1) {
				buffer[length] = (char) dec;
				length++;
			}
		}
		int modulus = length % 4;
		length -= modulus;
		byte[] result = new byte[length / 4 * 3
				+ (modulus < 2 ? 0 : modulus < 3 ? 1 : 2)];
		int j = 0;
		for (int i = 0; i < length; i += 4) {
			int b1 = buffer[i];
			int b2 = buffer[i + 1];
			int b3 = buffer[i + 2];
			int b4 = buffer[i + 3];
			result[j] = (byte) ((b1 << 2) | (b2 >> 4));
			j++;
			result[j] = (byte) ((b2 << 4) | (b3 >> 2));
			j++;
			result[j] = (byte) ((b3 << 6) | b4);
			j++;
		}
		if (modulus > 1) {
			int b1 = buffer[length];
			int b2 = buffer[length + 1];
			result[j] = (byte) ((b1 << 2) | (b2 >> 4));
			j++;
			if (modulus > 2) {
				int b3 = buffer[length + 2];
				result[j] = (byte) ((b2 << 4) | (b3 >> 2));
				j++;
			}
		}
		return result;
	}

	/**
	 * 将图片解析成数字
	 * 
	 * @param img
	 * @return
	 */
	public static String getChar(BufferedImage img) {
		String ret = null;
		BufferedImage imgx = removeBackgroud(img);
		ret = getImgCharOcr(imgx);
		return ret;
	}

	private static String getImgCharOcr(BufferedImage img) {
		String result = null;
		int width = img.getWidth();
		int height = img.getHeight();
		int min = width * height;
		for (BufferedImage trainedimg : characterMap.keySet()) {
			int count = 0;
			Label1: for (int x = 0; x < width; ++x) {
				for (int y = 0; y < height; ++y) {
					if (isWhite(img.getRGB(x, y)) != isWhite(trainedimg.getRGB(
							x, y))) {
						count++;
						if (count >= min)
							break Label1;
					}
				}
			}
			if (count < min) {
				min = count;
				result = characterMap.get(trainedimg);
			}
		}
		return result;
	}

	private static BufferedImage removeBackgroud(BufferedImage img) {
		int width = img.getWidth();
		int height = img.getHeight();
		for (int x = 0; x < width; ++x) {
			for (int y = 0; y < height; ++y) {
				if (isWhite(img.getRGB(x, y)) == 1) {
					img.setRGB(x, y, Color.WHITE.getRGB());
				} else {
					img.setRGB(x, y, Color.BLACK.getRGB());
				}
			}
		}
		return img;
	}

	private static int isWhite(int colorInt) {
		if (((0xff000000 | colorInt) ^ 0xffffffff) == 0) {
			return 1;
		}
		return 0;
	}

	// private static int isBlack(int colorInt) {
	// return 1 - isWhite(colorInt);
	// }
}
